## Teach Yourself ActiveX in 21 Days

- What is WinSock?
  - Background
    - History
    - Current Implementation
    - WinSock Vocabulary and Context
    - Winsock Technical Description
- WinSck.OCX
  - Purpose of the WinSock Control
  - Installation
  - Creating a WinSock TCP Server
  - Creating a WinSock Client
  - WinSock UDP
    - UDP Server
    - UDP Client
- Summary
- Q&A
- Workshop
  - Quiz

#
— 12 —

##
WinSock—Windows Network Programming

In this chapter you will learn what WinSock is. You will also learn how the WinSock control is used to create applications for TCP and UDP. When you are finished, you will be able to create:

- A TCP server and a TCP client application
- A UDP server and a UDP client application

###
What is WinSock?

WinSock (short for Windows Sockets) is the standard for programming network applications in Windows. All ActiveX programs use the routines in the WinSock .DLLs to access the TCP/IP stack. WinSock is meant to be a universal interface to the TCP/IP stream.

From a computer's perspective, sockets in programming work just like an electric socket. When a piece of software wants to get some juice from the network, it plugs into a stream and gets whatever it needs. You can never have any more connections than you have sockets, but the sockets are easy to install. Each additional connection requires more and more power (or bandwidth).

####
Background

Before I go into the nuts and bolts of how to use ActiveX WinSock features, here's a little background on WinSock.

#####
History

The University of California at Berkeley is known for all kinds of creative innovations (some more productive than others). The "sockets" concept of networking is one of the best.

Berkeley Software Distribution's UNIX was the first to incorporate socket style-routines. BSD UNIX was developed to be the universal interface to TCP/IP. Although it is still in wide use, it has fallen into a small niche as other network systems such as NetWare and Windows NT have taken a dominant position. The TCP/IP aspect of UNIX remains, though.

The task of taking this TCP/IP implementation to a Microsoft Windows machine was undertaken by a group of hobbyists and professionals. The planning sessions were held during a series of conferences in the early part of this decade. The WinSock standard was proposed in September of 1991. Research on it continued on until January 1993, when the version 1.1 specification was released. WinSock 2 is currently in its test phases and is planned for release in late 1996 or early 1997. It will be significantly, if not completely, backwards compatible with version 1.1

#####
Current Implementation

> > Note
> > Although the WinSock standard can, theoretically, provide an interface for programming over any network, it has mostly been used for programming Internet applications through TCP/IP.

The WinSock standard has been accepted by Microsoft as the official standard for programming TCP/IP applications in Windows. It is not, however, owned by Microsoft, as ActiveX is. While Microsoft did have a very strong voice in how WinSock was developed as a standard, WinSock has always been maintained by an independent organization. According to Microsoft's press releases, ActiveX will also be handed over to an independent standards body for continued maintenance and development.

#####
WinSock Vocabulary and Context

A WinSock supplier is the individual or organization that creates an application based on the Windows Sockets API.

An application is WinSock compliant if it adheres to all of the provisions in the WinSock 1.1 specification (about 200 pages). It must have at least one WinSock interface (or there is no reason to go through the trouble of adhering to the WinSock specification!). Any application that is WinSock compliant is called a WinSock application (of course).

#####
Winsock Technical Description

WinSock routines are only one level in the hierarchy of objects between you (the person) and the TCP/IP stream (see Figure 12.1).

Figure 12.1. There are many levels of communication that enable a user to retrieve remote data through a WinSock connection.

######
Hierarchy

First there is you, the user, and you are using a WinSock application (say it's your Web browser). You want to use this thing to get some information from the Internet, so your Web browser will need to access the TCP/IP stream, which is the lowest level of the hierarchy.

The TCP/IP stream has to come up from "out there" on the Net to your computer through a hardware interface. This is your modem or your network card—whichever you use to access the Internet.

After the stream gets in through the hardware, there is a piece of software that is usually part of the operating system. That is the driver for your network hardware.

This hardware driver monitors the network device as well as the application's software to determine what is talking to whom. "On top" of this hardware driver are the network stacks for whatever protocols you use on your computer. On a Windows95 machine, these are usually NetBEUI, NetBIOS and IPX/SPX. TCP/IP is also included for any Internet hosts.

Whatever other network stacks are used on a computer, every machine that accesses the Internet will have to have a TCP/IP stack as well. Your Web browser communicates with this stack. Obtaining this communication between your Web browser and the TCP/IP stack is the purpose of WinSock routines.

######
Functions

WinSock.DLL (also known as The WinSock Library) is a file on your hard drive that contains the socket functions. This library is the hard code for making the computer send the right 0s and 1s to the parts and pieces of your computer. By making calls to this file and monitoring its states, you can perform all the socket functions for communicating with TCP/IP. You will look at some of WinSock.DLL's more basic functions to acquaint yourself with its features.

When you run your Web browser, you are telling it to view different pages on the Web. This is conducted by typing a URL (Uniform Resource Locator). Within this URL is the name of the specific host on the Net from which you wish to retrieve the page. The name portion of the URL can be in the domain-name format (www.mcp.com) or in IP format (206.246.150.10).

If the domain name format is used, it will need to be resolved into the IP format, which is how hosts on the Net are uniquely identified to each other. (Only humans need the domain-name format to make this identification easier to remember.) To get the IP address, use the GetHostByName() function.

The WinSock GetHostByName() Function

    GetHostByName(Hostname)

The GetHostByName() function is used to retrieve the IP address of a specified host. This must be done before the connection can be made to the other system because computers use IP addresses instead of domain names to identify themselves to each other.

Example:

    GetHostByName(mcp.com)

This function would return:

    206.246.150.10

On a similar note, if you need to convert an IP Address to a host name, use the GetHostName() Function .

The WinSock GetHostName() Function

    GetHostName(IP Address)

The GetHostName() function is used to retrieve the domain name that is assigned to the specified host's IP address. This is used to make the identification of a specific host easy for the user.

Example:

    GetHostByName(206.246.150.10)

This function would return:

    mcp.com

###
WinSck.OCX

Implementation of the WinSock API into a user application can be quite complex because a tremendous number of interfaces are available. Requesting a connection, making the connection, communicating, and so on are each processes that involve many steps. States change as these steps are taken, and the application must monitor these states, acting accordingly.

In spite of this complexity, Windows Internet applications can be developed with relative ease when using a plug-in control such as the WinSck.OCX . This control takes over most of the difficult and repetitive tasks. This leaves the programmer free to code only the most application-specific features.

####
Purpose of the WinSock Control

The WinSock control can be used to program client or server machines. It can also be used in a special third mode called broadcast, which is a hybrid of the two.

####
Installation

The ICP (Internet Control Pack), included on the enclosed CD-ROM, contains controls for most of the more popular Internet protocols. The most powerful of these, and perhaps the most difficult to use, is the WinSock TCP/UDP control.

> > Note
> > To install the Internet Control Pack, double click the MSICPB.exe icon on the CD. When the automatic installation is complete, reboot your system as prompted.

All other controls in this package are client controls; they are used to connect to other machines that are waiting and monitoring the Net for connection requests. The WinSock UDP and TCP controls, however, can act as either client or server controls. If your application conforms to the proper specifications, it can even act as a server control for HTTP, FTP, SMTP, and all the others .

In the following sections you will examine the WinSock control's features for creating both a client and a server application in Visual Basic.

The first sample projects you will create are a message server and a client application. A message server takes messages for you while you are away from your computer, and a client application is used by others to send those messages to you.

####
Creating a WinSock TCP Server

To create the WinSock server, start with a brand new Visual Basic form. In the References option of the project, select Microsoft WinSock Controls. Then add the controls to the Visual Basic toolbar.

> > Note
> > Adding the Microsoft WinSock Controls to the toolbar places two icons on the toolbar. One is the TCP control and the other is the UDP control.

> > Hint
> > If the WinSock control is not on the list and you have installed the Internet Control Pack, follow these instructions:
> > 1. Locate the WinSck.ocx file on your hard drive.
> > 2. Run RegSvr32.exe and the location of the file from the command prompt (for example: RegSvr32 C:\Windows\System\WinSck.ocx).
> > 3. Pull up the References option in Visual Basic, and the control should be listed.

Next, add the labels , text boxes, buttons and so on (see Figure 12.2). These will include:

- Two command buttons; one named cmdClose and the other cmdListen.
- Two labels; one named lblConnections with a caption of 0.
- One list box named lstMessages.
- One TCP control named tcpListener.
- One TCP control array named tcpReceiver with a 0 index property.

Figure 12.2. The WinSock answering machine application uses several labels, text boxes and buttons as well as two copies of the WinSock control.

Now add code to the appropriate controls so that this application will take your messages for you.

First of all, tell the control to monitor one TCP/IP port to any incoming messages. For your answering machine, choose the random 1023 port. To tell the WinSock control to monitor that port, set the LocalPort property, then invoke the Listen method like so:

    Private Sub cmdListen_Click
     'Server starts monitoring port 1023when the Listen button is clicked
     tcpListener.LocalPort = 1023
     tcpListener.Listen
    End Sub

The WinSock TCP Control's Listen Method

    WinSock Control.LocalPort = Unused Port

    WinSock Control.Listen

The WinSock control's Listen method is used to command the control to monitor the local TCP/IP port as specified in the LocalPort property.

Example:

    tcpWinSock.LocalPort = 1025

    tcpWinSock.Listen

When a user sends a message (using the client application that you will write later in this chapter) the ConnectionRequest event is fired. When this happens, load a copy of the tcpReceiver control, leaving the tcpListener control free to handle any other incoming calls. To track how many incoming messages are arriving at one time, update the lblConnections counter.

    Private Sub tcpListener_ConnectionRequest (ByVal requestID as Long)
     'When a connection is requested, a Receiver control is loaded
     ‘and the Connections counter incremented.
     lblConnections.Caption=lblConnections.Caption + 1
     Load tcpReceiver(lblConnections.Caption)
     tcpReceiver(lblConnections.Caption).Accept requestID
    End Sub

The WinSock TCP Control's Accept Method

    WinSock Control(Index).Accept Connection ID

The WinSock control's Accept method is used to tell a control to accept an incoming request for a connection. A link to the connection request is passed to the control that is to accept the request.

Example:

    tcpWinSock(3).Accept 25

This will tell the fourth WinSock control to accept a connection request, identified as an integer.

After this code has executed, the connection between the client and the server is set.

The next step is to wait for the client application to send its message. When the server receives the message, the DataArrival event is fired. When this happens, invoke the WinSock control's GetData method to retrieve the message. The message is then added to the lstMessages list box for you to view. The message-taking code looks something like this:

    Private Sub tcpReceiver_DataArrival(Index as Integer, ByVal bytesTotal as Long)
    Dim msgDataIn
    'When data arrives it is sent directly to the Message List
     tcpReceiver(lblConnections.Caption).GetData msgDataIn, vbString
     lstMessages.AddItem msgDataIn
    End Sub

The WinSock TCP Control's GetData Method

    WinSock Control(Index).GetData Variable, VariableType

The WinSock control's GetData method is used to retrieve any data sent to the control from the remote client. The data is then sent to the user-specified variable.

Example:

    tcpWinSock(1).GetData strMyVariable, vbString

This will tell the second WinSock control to set the string-type value of vbMyVariable to whatever was received through the WinSock connection.

As soon as the client sends its message, it closes the socket. When this happens, decrease the Connections counter and unload the WinSock control that was using it like so:

    Private Sub tcpReceiver_Close(Index as Integer)
     'When the socket closes
     ‘the control is unloaded and the Connections counter is decreased.
     tcpReceiver(Index).Close
     Unload tcpReceiver(Index)
     lblConnections.Caption = lblConnections.Caption - 1
    End Sub

The WinSock TCP Control's Close Method

    WinSock Control(Index).Close

The WinSock control's Close method shuts down the connection between client and server. The control can then be unloaded, freeing network resources.

Example:

    tcpWinSock(25).Close
    UnLoad tcpWinSock(26)

This closes the 27th WinSock connection, then unloads the control.

> > Hint
> > The WinSock control's Close method might seem to be a redundant feature because the control is unloaded whenever the form is unloaded.
> > Actually, the Close method is important because it cleans up and closes up any loose connections to the network. This frees your network resources as soon as they are no longer needed.

After you compile this into an .EXE, your computer will be able to run the program and, after you press the Listen button, it will take incoming messages from the client program (which I will discuss now).

####
Creating a WinSock Client

To create the WinSock server, start with a brand new Visual Basic form. In the References option of the project, select Microsoft WinSock Controls. Then add the controls to the Visual Basic toolbar.

The next step is to add the labels, text boxes, buttons and such (see Figure 12.3). These will include:

- Two labels.
- Two text boxes; one named txtRemoteHost and the other named txtMessage.
- One command button named cmdSend.
- One TCP control named tcpSender.

Figure 12.3. Since it does not have to monitor a port, the WinSock message-sending application only uses one copy of the WinSock control.

Now add code to the appropriate controls so that you can send messages to the server program.

When the user has identified the IP address of the answering machine and entered his message in the text box, he presses the Send button to transmit the message to the server.

Since the program does not do anything until the user presses the button, you must add code to the Send button's Click event that tells it to connect to the answering machine like so:

    Private Sub cmdSend_Click
     'The user specified Answering Machine is called on port 1023
     tcpSender.Connect tcpRemoteHost, 1023
    End Sub

The WinSock TCP Control's Connect Method

    WinSock Control(Index) Server IP, Server Port

or

    WinSock Control(Index) RemoteHost = Server IP
    WinSock Control(Index) RemotePort = Server Port
    WinSock Control(Index) Connect

The WinSock control's Connect method is used by a control that is acting in client mode to request a connection to an Internet server. The IP address and the port on which it is listening can either be passed on the Connect command line, or their respective properties can be set before the Connect method is invoked.

Example:

    tcpMyClient. "204.181.96.53", 25

or

    tcpMyClient RemoteHost = "204.181.96.53"
    tcpMyClient RemotePort = 25
    tcpMyClient Connect

This instructs the WinSock control to request a client connection to the server at 204.181.96.53 on port 25.

As soon as the connection is made, send your data, and log off. This is done in the tcpSender control's Connect event like so:

    Private Sub tcpSender_Connect()
     'When a connection is made
     ‘the Message is transmitted and the socket is then closed.
     tcpSender.SendData txtMessage.Text
     tcpSender.Close
    End Sub

The WinSock TCP Control's SendData Method

    WinSock Control(Index).SendData Data String

The WinSock control's SendData method is used by the control in either client or server mode to transmit data to the remote connection.

Example:

    tcpMyClient.,SendData "I think therefore I am."

This instructs the WinSock control to send the data string "I think therefore I am." to a WinSock application running on the remote host.

After you compile this into an .EXE, you will be able to send a message from the Message box to any Internet host that is running the server program.

> > Note
> > A working sample of this WinSock client program can be found in the \VB4\WinSock directory on the CD-ROM included with this book.

####
WinSock UDP

When you load the WinSock control onto your Visual Basic toolbar, notice that it adds two icons—TCP and UDP. Each is capable of transferring data over the Internet.

The TCP control requires a user to request a connection to a server and have that connection accepted. The UDP control , however, does not require the request or acceptance of a connection; it simply broadcasts from a port to a host (or an array of hosts) on the network. If the hosts are listening, they receive the broadcast; if they are not they do not.

#####
UDP Server

To create the WinSock UDP server, start with a brand new Visual Basic form. In the References option of the project, select the Microsoft WinSock Controls reference. Then add the controls to the Visual Basic toolbar using Ctrl_T from Visual Basic's main window.

Figure 12.4. The WinSock UDP server answering machine form with the controls loaded and displayed.

After you select the right tools and references, add the labels, text boxes, buttons and so on (see Figure 12.4). For the server, these include:

- Two command buttons (named cmdClose and cmdListen).
- One list box named lstMessages.
- One text box named txtLocalPort.
- One WinSock UDP control named UDP.

When the form is laid out, add the code that allows the answering machine application to wait for incoming messages. In a UDP connection, this involves nothing more than setting the LocalPort property of the control. To make the Listen button await a connection, add the following code:

    Private Sub cmdListen_Click()
     UDP.LocalPort=872
    End Sub

When you have set the LocalPort of the UDP control, it fires a DataArrival event for each string received. In your answering machine application, add the incoming messages to the lstMessages list box.

    Private Sub UDP_DataArrival(ByVal bytesTotal as Long)
     Dim strDataIn
     UDP.GetData strDataIn, 8
     lstMessages.AddItem strDataIn
    End Sub

This application monitors the local port specified in the txtLocalPort.Text property. When data comes in through that port, it fires the DataArrival event, which adds the data string to the lstMessages list box.

#####
UDP Client

To create the WinSock UDP client , start with a brand new Visual Basic form. In the References option of the project, select the Microsoft WinSock Controls reference. Then add the controls to the Visual Basic toolbar using Ctrl_T from Visual Basic's main window.

Figure 12.5. WinSock UDP control loaded into the UDP message sending project.

After you select the right tools and references, add the labels, text boxes, buttons and so on (see Figure 12.5). For the message-sending application, these include:

- Four command buttons (named cmdSend, cmdQuit, cmdAdd and cmdRemove).
- One list box named lstHosts.
- One text box named txtMessage.
- One WinSock UDP control array named UDP.

When the form is laid out, add the code that allows this message-sending application to broadcast its message to a number of waiting answering machines.

In a UDP connection, this involves nothing more than setting the RemotePort and RemoteHost properties of the control and invoking the SendData method. Thus, to make the Send button broadcast a message, add the following code:

    Private Sub cmdSend_Click()
     For x = 1 to lstHosts.ListCount
     Load UDP(x)
     UDP(x).RemotePort = txtRemotePort.Text
     UDP(x).RemoteHost = lstHosts.ItemData(x-1)
     UDP(x).SendData txtMessage.Text
     Next x
    End Sub

The WinSock UDP Control's SendData Method

    WinSockLib.UDP(Index).RemoteHost = Remote IP
    WinSockLib.UDP(Index).RemotePort = Remote Port
    WinSockLib.UDP(Index).SendData Data String

The WinSock UDP control's SendData method is used by the server data to the remote connection(s) and on the specified port.

Example:

    udpMyClient.RemoteHost = "204.181.96.53"
    udpMyClient.RemotePort = 25
    udpMyClient.,SendData "I think therefore I am."

This instructs the WinSock UDP control to send the data string "I think therefore I am." The message is broadcasted to the remote machine only if the remote machine is currently monitoring the port.

This application sends one message to each RemoteHost in an array of UDP connections. Each of those hosts must be monitoring the same port as the message sender at the time of the broadcast to receive the message.

###
Summary

In this chapter you have learned about WinSock programming and how it applies to the Internet. You know about its beginnings as a proposed standard in 1991, and its future release in the WinSock 2 specification.

WinSock is used as a Windows programmer's interface to the TCP/IP suite of network protocols, including SMTP, FTP, NNTP, HTTP and others. Using the WinSock interface frees the programmer from having to coordinate a variety of network management functions that are automated in the WinSock library.

The WinSck.OCX file is one of the ActiveX custom controls installed with Microsoft's Internet Control Pack. It provides a simplified interface to the WinSock library to programmers in languages such as Visual Basic, Microsoft Access, and Visual FoxPro.

The WinSock control exposes features for two different kinds of Internet connections—TCP (Transmission Control Protocol) and UDP (User Datagram Protocol). TCP is host-to-host communication, and UDP is a broadcasted, "connectionless" form of communication.

Both TCP and UDP controls require a host on one system that is sitting idle awaiting a connection, and a client on another host that initiates the transaction.

###
Q&A

- Q Can the WinSock control be used as a complete WinSock interface?
- A No. The WinSock control only exposes an interface to the WinSock DLL file. If your want to access the WinSock routines directly, make API calls to the WinSock library through an interface such as a Visual Basic or Microsoft Access Module.
- Q How many connections (UDP and TCP) can you make at the same time?
- A This is limited by your system's resources. Each programming environment only allows a certain number of controls to be loaded at the same time. The number of connections is also limited by such factors as your system memory, and the bandwidth of your network connection.
- Q What changes will I have to make to work with the upcoming WinSock 2 specification?
- A Ideally, none. The implementation of the WinSock 2 API is planned to be backwards compatible. If you use the ICP WinSock control as your WinSock interface, your code will remain the same. But when it comes out, you will want to use the updated control to take advantage of any enhanced features of WinSock 2.
- Q How can I tell when a program is finished using the WinSock control?
- A The WinSock control, unlike others in the ICP, does not have a State or ProtocolState property. If you use this control, your application must determine when the transactions are complete. When they are, your application can unload the control, freeing system resources for other processes.

###
Workshop

The WinSock UDP control can be a very powerful tool for broadcasting information in real-time to a number of different users. For this exercise, you will create a broadcast server and a redistributable client that your users will run to receive those real-time broadcasts. Try to meet the following specifications:

- The program will use a TCP control in Listen mode, which will receive requests from each of the users when they wish to begin receiving your broadcasts.
- When the connection is requested, the control will identify the user's IP address, check it, and add it to a list object.
- The broadcast will be in audio format. To do this, add a wave audio control to your project. The operator will use your interface to the wave audio control to record a message, which will be stored to a file on disk.
- When the user initially connects to the server, the server will transmit the last audio file recorded back to the user. Then, whenever the audio file is updated, it will be broadcasted to each client identified in the list object.

####
Quiz

> > Note
> > Refer to the Appendix, "Answers to Quiz Questions," for the answers to these questions.

1. What is the original operating system that was designed as an interface to the TCP/IP network.
2. What is the name given to an application that uses a WinSock interface?
3. What two formats can be used to identify a host on the Internet?
4. What is the WinSock function that determines the IP address of a domain?
5. What two client/server interfaces are presented by the WinSock custom control in Visual Basic and Microsoft Access?
6. Which property on the WinSock TCP control is used by a server to identify the port it will monitor?
7. Which property of the WinSock UDP control is used by a server to identify the port it will monitor?
8. When a control is notified of an incoming connection request, what parameter(s) will it receive to take control of that connection?
9. When invoking the GetData method, what two parameters must be specified?
10. What method is used to terminate a WinSock session?